#include "stdafx.h"
#include "./luaex/luaex.h"
#include "io/winfile.h"
#include "./scriptmgr.h"

ScriptMgr::ScriptMgr()
: m_loaded(false)
{
	lua_State* luaState = lua_open();
	luaopen_base(luaState);
	luaopen_table(luaState);
	luaopen_string(luaState);
	luaopen_math(luaState);
	luaopen_debug(luaState);
	luaopen_os(luaState);

	LuaEx::GetInstance().SetLuaState(luaState);
}

ScriptMgr::~ScriptMgr()
{
	if (m_loaded)
	{
		ClearFiles();
	}
}

bool ScriptMgr::ReadLuaFiles(string strDir)
{
	bool bSucceed = WinFile::GetFolderFiles(strDir, m_strFiles);

	for (int i = static_cast<int>(m_strFiles.size()) - 1; i >= 0 ; --i)
	{
		string postfix = m_strFiles[i].substr(m_strFiles[i].length() - 4);
		if (postfix != ".lua")
		{
			vector<string>::iterator iter = m_strFiles.begin() + i;
			m_strFiles.erase(iter);
		}
	}

	for (size_t i = 0; i < m_strFiles.size(); ++i)
	{
		WinFile winFile;
		if (!winFile.OpenFile(strDir + m_strFiles[i], WinFile::IO_OPEN_READ))
		{
			m_buffers.push_back(NULL);
		}

		size_t filesize = winFile.ReadFile(NULL, 0);
	
		char* buffer = new char[filesize + 1];
		memset(buffer, 0, filesize + 1);
		winFile.ReadFile(reinterpret_cast<byte*>(buffer), filesize);

		m_buffers.push_back(buffer);
	}

	m_loaded = true;

	return bSucceed;
}

void ScriptMgr::ClearFiles()
{
	m_loaded = false;

	for (size_t i = 0; i < m_strFiles.size(); ++i)
	{
		delete m_buffers[i];
	}

	m_strFiles.clear();
	m_buffers.clear();
}

size_t ScriptMgr::GetLuaFileCount()
{
	if (!m_loaded)
	{
		return 0;
	}

	return m_strFiles.size();
}

string ScriptMgr::GetFileName(size_t index)
{
	if (!m_loaded)
	{
		return "";
	}

	return m_strFiles[index];
}

void ScriptMgr::LoadScript(string strName, size_t index)
{
	if (!m_loaded)
	{
		return;
	}

	Def_Module(strName.c_str())
	[
		Def_Script(m_buffers[index])
	];
}